# -*- coding: utf-8 -*-
"""
__mktime__ = '2019/4/21'
__author__ = 'Just'
__filename__ = 'banner_item'
"""
from datetime import datetime
from sqlalchemy import Column, Integer, String, orm, SmallInteger, ForeignKey
from app.libs.common import get_current_time
from app.libs.error_code import ParameterException
from app.model.base import BaseModel, db


class BannerItem(BaseModel):
    """轮播位模型"""
    __tablename__ = 'banner_item'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String(50), unique=True, comment='名称')
    description = Column(String(255), comment='执行关键字，根据不同的type含义不同')
    update_time = Column(Integer, comment='更新时间')
    type = Column(SmallInteger, default=1, comment='跳址类型 1:跳漫画信息,2跳分类页,3跳广告')
    link = Column(String(255), comment='跳转的地址')
    image = Column(String(255), comment='头图地址')
    bid = Column(SmallInteger, ForeignKey('banner.id'), comment='关联哪个banner id')

    @property
    def update_datetime(self):
        """时间转化"""
        if self.update_time:
            return datetime.fromtimestamp(self.update_time)
        else:
            return None

    @orm.reconstructor
    def __init__(self):
        # 序列化列表
        self.fields = ['bid', 'type', 'title',
                       'description', 'update_datetime',
                       'create_datetime', 'link', 'image', 'id']

    @classmethod
    def add_banner_item(cls, params):
        item = BannerItem.query.filter(BannerItem.title == params['title']).first()
        if item:
            raise ParameterException(msg='添加的banner子项名字重复, 添加失败', error_code=2011)
        with db.auto_commit():
            item = BannerItem()
            item.bid = params['bid']
            item.title = params['title']
            if params['description']:
                item.description = params['description']
            if params['type']:
                item.type = params['type']
            if params['link']:
                item.link = params['link']
            if params['image']:
                item.image = params['image']
            item.update_time = get_current_time()
            db.session.add(item)

    @classmethod
    def update_banner_item(cls, params):
        item = BannerItem.query.filter(BannerItem.title == params['title']).first()
        with db.auto_commit():
            if params['description']:
                item.description = params['description']
            if params['type']:
                item.type = params['type']
            if params['link']:
                item.link = params['link']
            if params['image']:
                item.image = params['image']
            item.update_time = get_current_time()
